<?php

/**
 * 自定义日志类
 * 生产模式无法确定错误具体位置，在指定业务逻辑上记录信息，便于排错
 * create at 2021/04/12
 */

namespace helper;
use think\contract\LogHandlerInterface;

//interface LogHandlerInterface
//{
//    /**
//     * 日志写入接口
//     * @access public
//     * @param  array $log 日志信息
//     * @return bool
//     */
//    public function save(array $log): bool;
//}

class Logdriver implements LogHandlerInterface
{
    /**
     * @param array $log
     * $log = [
     *  'filename' => '日志文件名',
     *  'msg' => '错误信息', 可以是数组或json字符串  一般为业务逻辑上的参数
     *  'mark' => '备注'
     * ];
     * @return bool
     * @throws \Exception
     */
    public function save(array $log): bool
    {
        // TODO: Implement save() method.
        $max_size = 2048*1000;
        $savelog = app()->getrootPath() .'/runtime/mylog/';
        if (!is_dir($savelog)) {
            mkdir($savelog, 0755, true);
            chmod($savelog, 0755);
        }

        if ($log['filename'] == "") {
            $log_filename = $savelog. date('Ym-d') . ".log";
        } else {
            $log_filename = $savelog. date('Ym-d').'-'.$log['filename'] . ".log";
        }
        if (file_exists($log_filename) && (abs(filesize($log_filename)) > $max_size)) {
            rename($log_filename, dirname($log_filename) . DS . date('Ym-d-His') . $log['filename'] . ".log");
        }
        $t = microtime(true);
        $micro = sprintf("%06d", ($t - floor($t)) * 1000000);
        $d = new \DateTime (date('Y-m-d H:i:s.' . $micro, $t));
        $log_content = $log['msg'];
        if(is_array($log['msg'])){
            $log_content = json_encode($log['msg'],320);
        }
        file_put_contents($log_filename, '[' . $d->format('Y-m-d H:i:s') . "] \t " . $log['mark'] . "\r\n" . $log_content . "\r\n------------------------ --------------------------\r\n", FILE_APPEND);
        return true;
    }
}